package com.dongdong.zhuangji.utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Scanner;

public class DrawImageToExcel{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入要显示的文字: ");
        String text = scanner.nextLine();
        System.out.print("请输入行数: ");
        int rows = scanner.nextInt();
        System.out.print("请输入每行的圆的数量: ");
        int circlesPerRow = scanner.nextInt();
        System.out.print("请输入图片要插入的起始列索引: ");
        int startCol = scanner.nextInt();
        System.out.print("请输入图片要插入的起始行索引: ");
        int startRow = scanner.nextInt();
        scanner.close();

        try {
            // 创建工作簿和工作表
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Sheet1");
            creatImage(rows, circlesPerRow, text, startCol, startRow, sheet, workbook);

            // 保存工作簿
            try (FileOutputStream fileOut = new FileOutputStream("workbook.xlsx")) {
                workbook.write(fileOut);
            }

            System.out.println("图片已成功嵌入 Excel 指定单元格。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param rows 行数
     * @param circlesPerRow 每行的圆的数量
     * @param text 文字
     * @param startCol 起始列索引
     * @param startRow 起始行索引
     * @param sheet 工作表
     * @param workbook 工作簿
     * @throws IOException
     */
    public static void creatImage(int rows, int circlesPerRow, String text, int startCol, int startRow, Sheet sheet, Workbook workbook) throws IOException {
        // 创建图片
        BufferedImage image = drawImage(rows, circlesPerRow, text);

        // 将图片嵌入指定单元格
        writeImageToExcel(image, startCol, startRow, rows, circlesPerRow, sheet, workbook);
    }

    public static BufferedImage drawImage(int rows, int circlesPerRow, String text) {
        // 设置图片的宽度和高度
        int width = 260;
        int height = 120;

        // 创建一个支持透明通道的 BufferedImage 对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        // 获取 Graphics2D 对象，用于在图片上进行绘图操作
        Graphics2D g2d = image.createGraphics();

        // 绘制两个蓝色的圆形，竖向排列
        g2d.setColor(Color.BLUE);
        int circleRadius = height / 4 - 10;
        int centerX = width / 2;
        int topCircleY = height / 4;
        int bottomCircleY = height - height / 4;
        g2d.drawOval(centerX - circleRadius, topCircleY - circleRadius, circleRadius * 2, circleRadius * 2);
        g2d.drawOval(centerX - circleRadius, bottomCircleY - circleRadius, circleRadius * 2, circleRadius * 2);

        // 设置字体并绘制文字，文字在圆中间
        g2d.setColor(Color.BLACK);
        Font font = new Font("宋体", Font.BOLD, 11);
        g2d.setFont(font);
        int stringWidth1 = g2d.getFontMetrics().stringWidth(text + "-1");
        int stringWidth2 = g2d.getFontMetrics().stringWidth(text + "-2");
        g2d.drawString(text + "-1", centerX - stringWidth1 / 2, topCircleY);
        g2d.drawString(text + "-2", centerX - stringWidth2 / 2, bottomCircleY);

        // 释放 Graphics2D 对象占用的资源
        g2d.dispose();

        return image;
    }
    public static void writeImageToExcel(java.awt.image.BufferedImage image, int startCol, int startRow, int rows, int circlesPerRow, Sheet sheet, Workbook workbook) throws java.io.IOException {
        // 创建一个字节数组输出流
        java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
        javax.imageio.ImageIO.write(image, "png", baos);
        byte[] imageBytes = baos.toByteArray();

        // 将图片添加到工作簿中
        int pictureIndex = workbook.addPicture(imageBytes, org.apache.poi.ss.usermodel.Workbook.PICTURE_TYPE_PNG);

        // 创建一个绘图对象
        org.apache.poi.ss.usermodel.Drawing drawing = sheet.createDrawingPatriarch();

        // 创建一个锚点，设置为与单元格绑定
        org.apache.poi.ss.usermodel.CreationHelper helper = workbook.getCreationHelper();
        org.apache.poi.ss.usermodel.ClientAnchor anchor = helper.createClientAnchor();

        // 计算合并单元格的范围（这里假设是一个矩形区域，根据行数和每行圆的数量来确定）
        int endCol = startCol + circlesPerRow - 1;
        int endRow = startRow + rows - 1;

        // 计算合并单元格的中心列和中心行
        int centerCol = (startCol + endCol) / 2;
        int centerRow = (startRow + endRow) / 2;

        // 设置锚点的起始位置为合并单元格的中心
        anchor.setCol1(centerCol);
        anchor.setRow1(centerRow);

        // 更精确地计算结束列和结束行，根据图片的宽度和高度调整
        int colWidth = 256 * 10; // 假设列宽为 10 个字符宽度
        int rowHeight = 20 * 20; // 假设行高为 20 个像素
        int newEndCol = centerCol + (image.getWidth() * 256 / colWidth);
        int newEndRow = centerRow + (image.getHeight() * 20 / rowHeight);

        anchor.setCol2(newEndCol);
        anchor.setRow2(newEndRow);

        anchor.setAnchorType(org.apache.poi.ss.usermodel.ClientAnchor.AnchorType.MOVE_AND_RESIZE);

        // 创建图片并设置锚点
        org.apache.poi.ss.usermodel.Picture picture = drawing.createPicture(anchor, pictureIndex);
        picture.resize();
    }
}